package service;


import dao.UserDao;
import domain.User;
import exception.LoginException;
import exception.RegisterException;
import utils.MailUtils;
import utils.ResponseCode;

import javax.mail.MessagingException;
import javax.mail.internet.AddressException;
import java.sql.SQLException;

//业务处理
public class UserService {
    private UserDao userDao = new UserDao();

    public void activeUser(String activeCode) throws SQLException{
        userDao.activeUser(activeCode);
    }
    User userDB=null;
    public void register(User user) throws RegisterException {
        try {
            userDB = userDao.findUserByUsername(user.getUsername());

        }catch (SQLException e){
            throw new RegisterException(ResponseCode.ERROR_DB);
        }
        if (userDB==null){
            //添加记录
            try {
                userDao.addUser(user);
                String msg="感谢您注册网上书城，点击 <a href='http://localhost:8080/bookstore/activeUser?activeCode= "+user.getActiveCode()+"'>&nbsp;激活&nbsp;</a>后使用。 <br />为保障您的账户安全，请在24小时内完成激活操作;";
                MailUtils.sendMail(user.getEmail(),msg);
            }catch (SQLException e){
                throw new RegisterException(ResponseCode.ERROR_DB);
            }catch (AddressException e){
                //删除已经插入的记录
                try {
                    userDao.delUser(user.getActiveCode());
                }catch (SQLException ee) {
                    throw new RegisterException(ResponseCode.ERROR_PARANS);
                }
            }catch (MessagingException e){
                //
                try {
                    userDao.delUser(user.getActiveCode());
                }catch (SQLException ee) {
                    throw new RegisterException(ResponseCode.ERROR_EMAIL_END);
                }
            }

        }else {
            throw new RegisterException(ResponseCode.ERROR_USERNAME);
        }
    }

    public void login(User user)throws LoginException {
        try {
            User userDB = userDao.findUserByUsernameAndPassword(user.getUsername(), user.getPassword());
            if (userDB == null) {
                throw new LoginException(ResponseCode.NOT_USER_OR_PASSWORD);
            } else {
                if (userDB.getState() == 1) {

                } else {
                    throw new LoginException(ResponseCode.NOT_ACTIVE);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
            throw new LoginException(ResponseCode.ERROR_DB);
        }

    }

}
